package com.esp.soccertutor.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;

import com.esp.soccertutor.R;
import com.esp.soccertutor.android.fbreader.FBReader;
import com.esp.soccertutor.ui.VideoPlayer;
import com.esp.soccertutor.zlibrary.core.filesystem.ZLFile;

public class DownloadingFile extends AsyncTask<Void, Integer, Integer> {
	
	private String TAG = DownloadingFile.class.getCanonicalName();
	private int MODE;
	private Context mContext;
	private ProgressDialog mProgressDialog;
	private String filesource,filename;
	private int TypeID;
	
	public DownloadingFile(Context context,String filesource,String filename,int TypeID,int Mode) {
		mContext = context;
		this.filesource = filesource;
		this.filename = filename;
		this.TypeID = TypeID;
		MODE = Mode;
	}
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		mProgressDialog = new ProgressDialog(mContext);
		mProgressDialog.setMessage(mContext.getString(R.string.ProgressMessage));
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgressDialog.setCancelable(false);
		mProgressDialog.show();
	}
	@Override
	protected Integer doInBackground(Void... params) {
		
		int errorNo = 0;
		try
		{
			if ((errorNo = this.downloadFile(filesource,filename)) == 0) {
				//Complete Download then encrypt file 
				Log.print(TAG," *** DOWNLOAD COMPLETE  ****");
				
				if(MODE == Const.INT_PURCHASE){
					
					SimpleProtector encrypter = new SimpleProtector();
					boolean encryDone = encrypter.encrypt(new FileInputStream(Const.CATCH_DIR + "/" + filename),new FileOutputStream(Const.LIB_DIR + "/" + filename));
					if(encryDone){
						Log.print(TAG," *** Encrypter fine done  ****");
						boolean result = Storage.IsFileAvailableDelete(Const.CATCH_DIR + "/" + filename);
						if(result){
							Log.print(TAG," *** DELETE FILE COMPLETE  ****");
							return  errorNo;
						}else{
							return errorNo;
						}
					}
					
				}else{
					
					return  errorNo;
				}
				
					
			}
			
		}catch (Exception e) {
			e.printStackTrace();
			errorNo = 100103;
		}
	
		return errorNo;
	}
	
	@Override
	protected void onPostExecute(Integer result) {
		super.onPostExecute(result);
		mProgressDialog.dismiss();
		if (result == 0) {
			// Download Complete
			Toast.makeText(mContext,"Download Completed",Toast.LENGTH_LONG).show();
			if(TypeID == Const.TYPEID_EBOOKS){
				//START READING BOOKS
				ZLFile myFile = ZLFile.createFileByPath(Const.LIB_DIR + "/"
						+ filename);
				mContext.startActivity(new Intent(mContext, FBReader.class)
							.setAction(Intent.ACTION_VIEW)
							.putExtra(FBReader.BOOK_PATH_KEY, myFile.getPath())
							.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
					);
				
				
				
				
				
			}else if(TypeID == Const.TYPEID_VIDEOS){
				
				//START PLAYING VIDEOS
				Intent mIntent = new Intent(mContext,VideoPlayer.class);
				mIntent.putExtra("filename",filename);
				mContext.startActivity(mIntent);
				
				
			}
			
		} else if (result == 100101){
			Toast.makeText(mContext,"Unable to downlaod book",Toast.LENGTH_LONG).show();
		} else if (result == 100102){
			Toast.makeText(mContext,"Download Book: No response from the server, please try after sometime...",Toast.LENGTH_LONG).show();
		} else if (result == 100103){
			Toast.makeText(mContext,"Error Please try again ",Toast.LENGTH_LONG).show();
		}  
	}
	public int downloadFile(String filesource,String filename) {
		URL url = null;
		int errorNo = 0;
		HttpURLConnection conn = null;
		InputStream is = null;
		byte[] buffer = null;
		FileOutputStream fos = null;
		ByteArrayOutputStream bos = null;

		try {
			
			// set the download URL, a URL that points to a file on the Internet
			// this is the file to be Download
			
			url = new URL(filesource);
			// create the new connection
			conn = (HttpURLConnection) url.openConnection();

			if ((conn).getResponseCode() == HttpURLConnection.HTTP_OK) {
				// set up some things on the connection
				//conn.setRequestMethod("GET");
				//conn.setDoOutput(true);

				// and connect!
				conn.connect();

				int fileSize = conn.getContentLength();
				bos = new ByteArrayOutputStream(1);

				is = conn.getInputStream();

				Log.print(TAG,"total Size : " + fileSize);

				// set the path where we want to save the file in this case,
				// going to save it on the root directory of this sd card.
				// create a new file, specifying the path, and the filename
				// which we want to save the file as.
				Storage.veirfyLibPath();
				Log.print(TAG,"[ FILE PATH ] "+ Const.CATCH_DIR + "/" + filename );
				fos = new FileOutputStream(Const.CATCH_DIR + "/" + filename);
				
				buffer = new byte[2048];

				long downloaded = 0;
				int read = 0;
				while ((read = is.read(buffer)) != -1) {
					fos.write(buffer, 0, read);
					
					downloaded += read;
					
					this.publishProgress((int) ((downloaded * 100) / fileSize));
					
				}

			} else {
				// no response from the server
				errorNo = 100102;
			}
		} catch (Exception e) {
			// Unable to download book
			e.printStackTrace();
			errorNo = 100101;
			Log.error(this.getClass() + ":: downloadEpubFile()", e);
		} finally {
			if (conn != null) {
				conn.disconnect();
			}

			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
			
			if (bos != null){
				try {
					bos.close();
				} catch (IOException e) {
				}
			}

			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
		}

		conn = null;
		is = null;
		fos = null;
		bos = null;
		buffer = null;
		url = null;

		return errorNo;
	}
	@Override
	protected void onProgressUpdate(Integer... values) {
		mProgressDialog.setProgress(values[0]);
	}
}


